<template>
  <div class='app-container'>
    <div style="text-align: center;">
      <el-radio-group
        v-model="tabPosition"
        @change="changeTab()"
      >
        <el-radio-button label="left">用户统计</el-radio-button>
        <el-radio-button label="right">销售统计</el-radio-button>
      </el-radio-group>
    </div>
    <div
      style="text-align:right;"
      v-show="tabPosition=='right'"
    >
      <el-upload
        class="upload-demo"
        :action="uploadUrl"
        name="excelFile"
        :on-success="handleAvatarSuccess"
        :show-file-list="false"
        :headers="imgHeaders"
      >
        <el-button
          size="small"
          type="text"
        >上传数据</el-button>
      </el-upload>
    </div>
    <section v-show="tabPosition == 'left'">
      <div class="data_section left-tab">
        <el-row :gutter="20">
          <el-col
            :sm="12"
            :md="4"
            class="mb-4 "
          >
            <div class="grid-content bg-purple card-small today_head">
              <div class="d-flex card-body">
                <div class="m-auto d-flex flex-column ">
                  <h6 class="stats-small__value text-center">当日数据</h6>
                </div>
              </div>
            </div>
          </el-col>
          <el-col
            :sm="12"
            :md="4"
            class="mb-4"
          >
            <div class="grid-content bg-purple card-small">
              <div class="d-flex card-body">
                <div class="m-auto d-flex flex-column ">
                  <span class="stats-small__label  text-center">新增用户</span>
                  <h6 class="stats-small__value text-center">{{newChartData.dayAddUser}}</h6>
                </div>
              </div>
            </div>
          </el-col>
          <el-col
            :sm="12"
            :md="4"
            class="mb-4"
          >
            <div class="grid-content bg-purple card-small">
              <div class="d-flex card-body">
                <div class="m-auto d-flex flex-column ">
                  <span class="stats-small__label  text-center">新增绑定设备</span>
                  <h6 class="stats-small__value text-center">{{newChartData.dayAddEquipment}}</h6>
                </div>
              </div>
            </div>
          </el-col>
          <el-col
            :sm="12"
            :md="4"
            class="mb-4"
          >
            <div class="grid-content bg-purple card-small">
              <div class="d-flex card-body">
                <div class="m-auto d-flex flex-column ">
                  <span class="stats-small__label  text-center">新增检测次数</span>
                  <h6 class="stats-small__value text-center">{{newChartData.dayDetection}}</h6>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col
            :sm="12"
            :md="4"
            class="mb-4"
          >
            <div class="grid-content bg-purple card-small all_head">
              <div class="d-flex card-body">
                <div class="m-auto d-flex flex-column">
                  <h6 class="stats-small__value text-center">总数据</h6>
                </div>
              </div>
            </div>
          </el-col>
          <el-col
            :sm="12"
            :md="4"
            class="mb-4"
          >
            <div class="grid-content bg-purple card-small">
              <div class="d-flex card-body">
                <div class="m-auto d-flex flex-column ">
                  <span class="stats-small__label  text-center">注册用户</span>
                  <h6 class="stats-small__value text-center">{{totalChartData.totalUser}}</h6>
                </div>
              </div>
            </div>
          </el-col>
          <el-col
            :sm="12"
            :md="4"
            class="mb-4"
          >
            <div class="grid-content bg-purple card-small">
              <div class="d-flex card-body">
                <div class="m-auto d-flex flex-column ">
                  <span class="stats-small__label  text-center">绑定设备</span>
                  <h6 class="stats-small__value text-center">{{totalChartData.totalEquipment}}</h6>
                </div>
              </div>
            </div>
          </el-col>
          <el-col
            :sm="12"
            :md="4"
            class="mb-4"
          >
            <div class="grid-content bg-purple card-small">
              <div class="d-flex card-body">
                <div class="m-auto d-flex flex-column ">
                  <span class="stats-small__label  text-center">检测次数</span>
                  <h6 class="stats-small__value text-center">{{totalChartData.totalDetection}}</h6>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <homeChart
        :id="'home'"
        :data='option'
        v-if="tabPosition==='left'"
      ></homeChart>
    </section>
    <section v-show="tabPosition=='right'">
      <div class="data_section">
        <el-row :gutter="20">
          <el-col
            :sm="12"
            :md="3"
            class="mb-4"
          >
            <div class="grid-content bg-purple card-small">
              <div class="d-flex card-body today_head">
                <div class="m-auto d-flex flex-column ">
                  <h6 class="stats-small__value text-center">本周数据</h6>
                  <span class="stats-small__label  text-center">（周日起始）</span>
                </div>
              </div>
            </div>
          </el-col>
          <el-col
            :sm="12"
            :md="3"
            class="mb-4"
            v-for="(item,index) in ovuolaChartData"
            :key="index"
          >
            <div
              class="grid-content bg-purple card-small"
              @click="goDetail(index+1)"
            >
              <div class="d-flex card-body">
                <div class="m-auto d-flex flex-column">
                  <span class="stats-small__label  text-center">{{item.name}}</span>
                  <h6 class="stats-small__value text-center">{{item.week}}</h6>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col
            :sm="12"
            :md="3"
            class="mb-4"
          >
            <div class="grid-content bg-purple card-small">
              <div class="d-flex card-body all_head">
                <div class="m-auto d-flex flex-column ">
                  <h6 class="stats-small__value text-center">总数据</h6>
                </div>
              </div>
            </div>
          </el-col>
          <el-col
            :sm="12"
            :md="3"
            class="mb-4"
            v-for="(item,index) in ovuolaChartData"
            :key="index"
          >
            <div
              class="grid-content bg-purple card-small"
              @click="goDetail(index+1)"
            >
              <div class="d-flex card-body">
                <div class="m-auto d-flex flex-column">
                  <span class="stats-small__label  text-center">{{item.name}}</span>
                  <h6 class="stats-small__value text-center">{{item.total}}</h6>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div style="text-align:right;">
        <el-select
          v-model="ovuoleChartSelectValue"
          @change="getOvuolaChartData()"
          placeholder="请选择"
        >
          <el-option
            v-for="item in ovuoleChartSelectoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <homeChart
        :id="'ovuola'"
        :data='ovuolaOption'
        v-if="tabPosition==='right'"
      ></homeChart>
    </section>

    <div class="chart-select-date">
      <el-button @click="changeMonth('2')">全部数据</el-button>
      <el-button @click="changeMonth('0')">近三个月</el-button>
      <el-button @click="changeMonth('1')">近一年</el-button>
      <el-date-picker
        v-model="chartPickerDate"
        @change="changeDatePicker()"
        type="daterange"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
        :default-time="['00:00:00', '23:59:59']"
      >
      </el-date-picker>
    </div>
  </div>
</template>

<script>
import homeChart from "@/components/EasyChart";
import format from "date-format";
import {
  fetchHome,
  fetchHomeChart,
  fetchOvuolaData,
  fetchOvuolaChartData
} from "@/api/chart";
import { getToken } from "@/utils/auth";
import { setStore, getStore, getPreMonthDay } from "@/utils/common";
export default {
  data() {
    return {
      chartPickerDate: [],
      option: null,
      sevenData: [],
      newChartData: {},
      totalChartData: {},
      tabPosition: !getStore("tabs") ? "left" : getStore("tabs"),
      ovuolaChartData: [],
      totalOvuolaChartData: [],
      ovuolaOption: null,
      sevenWeekData: [],
      uploadUrl: "",
      imgHeaders: {
        Authorization: ""
      },
      homeChartTitle: "",
      nowChartDate: {
        start: "",
        end: "",
        searchType: ""
      },
      ovuoleChartSelectTitle: "佑蜜",
      ovuoleChartSelectValue: "0",
      ovuoleChartSelectoptions: [
        {
          value: "0",
          label: "佑蜜销售"
        },
        {
          value: "1",
          label: "采集头销售"
        },
        {
          value: "2",
          label: "吸管销售"
        }
      ]
    };
  },
  components: {
    homeChart
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      //初始化三个月
      const idate = new Date(new Date().getTime());
      const date = format("yyyy-MM-dd", idate);
      this.homeChartTitle = "近三个月";
      this.nowChartDate.start = getPreMonthDay(date, 3);
      this.nowChartDate.end = date;
      this.nowChartDate.searchType = "2";

      this.getHomeData();
      this.getHomeChartData();
      this.getOvuolaData();
      this.getOvuolaChartData();

      //上传链接
      this.uploadUrl = process.env.BASE_API + "report/sales/upload";
      this.imgHeaders.Authorization = getToken();
    },
    handleAvatarSuccess(res, file, fileList) {
      if (res.status === 200) {
        this.$message.success("上传成功！");
      } else {
        this.$message.error(res.msg);
      }
    },
    goDetail(e) {
      this.$router.push({
        path: "/dataManage/historyOvuolaDataList",
        query: { id: e }
      });
    },
    ovuolaDataOption() {
      const colors = ["#5793f3", "#675bba", "#d14a61"];
      if (this.ovuoleChartSelectValue === "0") {
        this.ovuoleChartSelectTitle = "佑蜜";
      } else if (this.ovuoleChartSelectValue === "1") {
        this.ovuoleChartSelectTitle = "采集头";
      } else if (this.ovuoleChartSelectValue === "2") {
        this.ovuoleChartSelectTitle = "吸管";
      }
      this.ovuolaOption = {
        color: colors,
        title: {
          text: this.ovuoleChartSelectTitle + this.homeChartTitle + "销售视图"
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: ["天猫销售", "微盟销售", "小红书销售", "拼多多销售"]
        },
        xAxis: {
          type: "category",
          data: this.sevenWeekData[3],
          // boundaryGap: false,
          splitLine: { show: false }
        },
        yAxis: [
          {
            name: "销售量",
            type: "value",
            splitLine: { show: false },
            max: function(value) {
              return Math.ceil(value.max + value.max * 0.2);
            }
          }
        ],
        series: [
          {
            name: "微盟销售",
            type: "line",
            smooth: true,
            label: {
              normal: {
                show: true,
                position: "top",
                color: "#535a6d"
              }
            },
            itemStyle: {
              normal: {
                color: "#e49ea5"
              }
            },
            data: this.sevenWeekData[0]
          },
          {
            name: "天猫销售",
            type: "line",
            smooth: true,
            label: {
              normal: {
                show: true,
                position: "top",
                color: "#535a6d"
              }
            },
            itemStyle: {
              normal: {
                color: "#818181"
              }
            },
            data: this.sevenWeekData[1]
          },
          {
            name: "小红书销售",
            type: "line",
            smooth: true,
            label: {
              normal: {
                show: true,
                position: "top",
                color: "#535a6d"
              }
            },
            itemStyle: {
              normal: {
                color: "#de79b9"
              }
            },
            data: this.sevenWeekData[2]
          },
          {
            name: "拼多多销售",
            type: "line",
            smooth: true,
            label: {
              normal: {
                show: true,
                position: "top",
                color: "#fc475d"
              }
            },
            itemStyle: {
              normal: {
                color: "#fc475d"
              }
            },
            data: this.sevenWeekData[4]
          }
        ]
      };
    },
    userDataOption() {
      const colors = ["#5793f3", "#675bba", "#d14a61"];
      this.option = {
        color: colors,
        title: {
          text: "用户" + this.homeChartTitle + "数据视图"
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: ["新增用户", "新增绑定设备", "新增检测次数"]
        },
        xAxis: {
          type: "category",
          data: this.sevenData[3],
          // boundaryGap: false,
          splitLine: { show: false }
        },
        yAxis: [
          {
            name: "数量",
            type: "value",
            splitLine: { show: false },
            max: function(value) {
              return Math.ceil(value.max + value.max * 0.2);
            }
          },
          {
            name: "次数",
            type: "value",
            splitLine: { show: false },
            max: function(value) {
              return Math.ceil(value.max + value.max * 0.2);
            }
          }
        ],
        series: [
          {
            name: "新增用户",
            type: "bar",
            smooth: true,
            label: {
              normal: {
                show: true,
                position: "top",
                color: "#57556d"
              }
            },
            itemStyle: {
              normal: {
                color: "#62b46c"
              }
            },
            data: this.sevenData[0]
          },
          {
            name: "新增绑定设备",
            type: "bar",
            smooth: true,
            label: {
              normal: {
                show: true,
                position: "top",
                color: "#57556d"
              }
            },
            itemStyle: {
              normal: {
                color: "#efb563"
              }
            },
            data: this.sevenData[1]
          },
          {
            name: "新增检测次数",
            type: "line",
            yAxisIndex: 1,
            smooth: true,
            label: {
              normal: {
                show: true,
                position: "top",
                color: "#57556d"
              }
            },
            itemStyle: {
              normal: {
                color: "#d386b4"
              }
            },
            data: this.sevenData[2]
          }
        ]
      };
    },
    changeTab() {
      setStore("tabs", this.tabPosition);
    },

    //自定义时间
    changeDatePicker() {
      this.nowChartDate.start = this.chartPickerDate[0];
      this.nowChartDate.end = this.chartPickerDate[1];
      this.homeChartTitle = "自定义";
      this.nowChartDate.searchType = "4";
      if (this.tabPosition === "left") {
        this.getHomeChartData();
      } else {
        this.getOvuolaChartData();
      }
    },
    //选择时间段
    changeMonth(id) {
      const idate = new Date(new Date().getTime());
      const date = format("yyyy-MM-dd", idate);
      if (id === "0") {
        this.nowChartDate.start = getPreMonthDay(date, 3);
        this.nowChartDate.end = date;
        this.homeChartTitle = "近三个月";
        this.nowChartDate.searchType = "2";
        if (this.tabPosition === "left") {
          this.getHomeChartData();
        } else {
          this.getOvuolaChartData();
        }
      } else if (id === "1") {
        const earlyYear = date.split("-")[0] - 1;
        this.nowChartDate.start =
          earlyYear + "-" + date.split("-")[1] + "-" + date.split("-")[2];
        this.nowChartDate.end = date;
        this.homeChartTitle = "近一年";
        this.nowChartDate.searchType = "3";
        if (this.tabPosition === "left") {
          this.getHomeChartData();
        } else {
          this.getOvuolaChartData();
        }
      } else if (id === "2") {
        this.nowChartDate.start = "";
        this.nowChartDate.end = "";
        this.homeChartTitle = "全部";
        this.nowChartDate.searchType = "1";
        if (this.tabPosition === "left") {
          this.getHomeChartData();
        } else {
          this.getOvuolaChartData();
        }
      }
    },
    //销售图表
    async getOvuolaChartData() {
      if (this.nowChartDate.searchType !== "1") {
        this.nowChartDate.start = this.nowChartDate.start + " 00:00:00";
        this.nowChartDate.end = this.nowChartDate.end + " 00:00:00";
      }
      const res = await fetchOvuolaChartData({
        start: this.nowChartDate.start,
        end: this.nowChartDate.end,
        searchType: this.nowChartDate.searchType
      });
      if (res.status == "200") {
        if (res.data.length === 0) {
          this.$message({
            type: "error",
            message: "暂无数据"
          });
          return;
        }
        //0佑蜜1采集头2西关3时间4拼多多
        const apiArr = [[], [], [], [], []];
        res.data.forEach((item, index) => {
          if (this.ovuoleChartSelectValue === "0") {
            apiArr[0].unshift(item.wOvuola);
            apiArr[1].unshift(item.tOvuola);
            apiArr[2].unshift(item.rOvuola);
            apiArr[4].unshift(item.pOvuola);
          } else if (this.ovuoleChartSelectValue === "1") {
            apiArr[0].unshift(item.wHead);
            apiArr[1].unshift(item.tHead);
            apiArr[2].unshift(item.rHead);
            apiArr[4].unshift(item.pHead);
          } else if (this.ovuoleChartSelectValue === "2") {
            apiArr[0].unshift(item.wStraw);
            apiArr[1].unshift(item.tStraw);
            apiArr[2].unshift(item.rStraw);
            apiArr[4].unshift(item.pStraw);
          }
          apiArr[3].unshift(item.time);
        });
        this.sevenWeekData = apiArr;
        this.ovuolaDataOption();
      }
    },
    //销售顶部看板数据
    async getOvuolaData() {
      const res = await fetchOvuolaData();
      if (res.status == "200") {
        this.ovuolaChartData = [];
        let data1 = {};
        let data2 = {};
        let data3 = {};
        let data4 = {};
        let data5 = {};
        let data6 = {};

        data1.name = "佑蜜";
        data1.week = res.data[0].weekOvuola;
        data1.total = res.data[0].totalOvuola;
        this.ovuolaChartData.push(data1);
        data2.name = "采集头";
        data2.week = res.data[0].weekHead;
        data2.total = res.data[0].totalHead;
        this.ovuolaChartData.push(data2);
        data3.name = "吸管";
        data3.week = res.data[0].weekStraw;
        data3.total = res.data[0].totalStraw;
        this.ovuolaChartData.push(data3);
        data4.name = "公众号咨询人数";
        data4.week = res.data[0].weekPubConsult;
        data4.total = res.data[0].totalPubConsult;
        this.ovuolaChartData.push(data4);
        data5.name = "天猫咨询人数";
        data5.week = res.data[0].weekTConsult;
        data5.total = res.data[0].totalTConsult;
        this.ovuolaChartData.push(data5);
        data6.name = "拼多多咨询人数";
        data6.week = res.data[0].weekPingConsult;
        data6.total = res.data[0].totalPingConsult;
        this.ovuolaChartData.push(data6);
      }
    },
    //用户图表
    async getHomeData() {
      let res = await fetchHome();
      if (res.status == "200") {
        this.newChartData.dayAddEquipment = res.data[0].dayAddEquipment;
        this.newChartData.dayDetection = res.data[0].dayDetection;
        this.newChartData.dayAddUser = res.data[0].dayAddUser;
        this.totalChartData.totalEquipment = res.data[0].totalEquipment;
        this.totalChartData.totalDetection = res.data[0].totalDetection;
        this.totalChartData.totalUser = res.data[0].totalUser;
        this.userDataOption();
      }
    },
    //用户顶部看板数据
    async getHomeChartData() {
      if (this.nowChartDate.searchType !== "1") {
        this.nowChartDate.start = this.nowChartDate.start + " 00:00:00";
        this.nowChartDate.end = this.nowChartDate.end + " 00:00:00";
      }
      let res = await fetchHomeChart({
        start: this.nowChartDate.start,
        end: this.nowChartDate.end,
        searchType: this.nowChartDate.searchType
      });
      if (res.status == "200") {
        if (res.data.length === 0) {
          this.$message({
            type: "error",
            message: "暂无数据"
          });
          return;
        }
        console.log(res.data);
        const apiArr = [[], [], [], []];
        res.data.forEach(item => {
          apiArr[0].unshift(item.addUsers);
          apiArr[1].unshift(item.addEquipments);
          apiArr[2].unshift(item.detections);
          apiArr[3].unshift(item.time);
        });
        this.sevenData = apiArr;
        this.userDataOption();
      }
    }
  }
};
</script>

<style lang="less">
.data_section {
  padding: 20px 40px;
  margin-bottom: 40px;
  .grid-content {
    cursor: pointer;
  }
  .today_head {
    background: #ff9800;
    color: #fff;
    cursor: auto;
    span {
      color: #fff;
    }
  }
  .all_head {
    background: #20a0ff;
    color: #fff;
    cursor: auto;
  }
}
.left-tab {
  .grid-content {
    cursor: auto;
  }
}
.chart-select-date {
  text-align: center;
}
</style>
